import React, { useState, useEffect, useRef } from 'react';
import { connect } from 'dva';
import { Tree, Skeleton, Spin, Input, Icon, Tooltip, Modal, message } from 'antd';
import request from '@/utils/request';
import ScrollBar from '@/components/ScrollBar';
import styles from '../styles.less';
import PubSub from 'pubsub-js';
import remove from 'lodash/remove';
import findIndex from 'lodash/findIndex';
// import 'antd/dist/antd.css';

const { TreeNode, DirectoryTree } = Tree;
const { Search } = Input;

const namespace = 'formManage';
const eventName = 'formManage_catalogInfo';

function CatalogInfo(props) {
  const [TreeData, setTreeData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [selectedKeysArr, setSelectedKeysArr] = useState(['']);

  const [expandedKeys, setExpandedKeys] = useState([]);
  const [autoExpandParent, setAutoExpandParent] = useState(true);

  const [searchValue, setSearchValue] = useState('');

  // 补充：通过dva来传递选中节点的数据，主要是功能组件的组件编码校验，及功能组件的新增删除接口入参
  const saveSelectCatalog = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveSelectCatalog`,
      payload: params,
    });
  };

  // 通过dva来判断当前节点是否为最后一级节点
  const saveIsLeaf = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveIsLeaf`,
      payload: params,
    });
  };

  // 通过dva传递菜单列表数据，给菜单信息的菜单上级的下拉框使用
  const saveTreeData = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveTreeData`,
      payload: params,
    });
  };

  // 通过dva来保存当前的操作状态  值:true/false
  const saveCatalogAddVisible = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveCatalogAddVisible`,
      payload: params,
    });
  };

  // 通过dva来保存当前的操作状态  值:add/edit/addSon
  const saveCatalogAddType = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveCatalogAddType`,
      payload: params,
    });
  };

  // 通过dva传递菜单列表数据，表单按钮使用
  const saveCatalogButton = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveCatalogButton`,
      payload: params,
    });
  };

  useEffect(() => {
    queryTreeData();
    PubSub.subscribe(`${eventName}.update`, (eventName, data) => {
      let arr = data.treeData;
      let node = data.dataList;
      // data.dataList.menuType === '1000' ? (
      node.isLeaf = false;
      // ) : (node.isLeaf = true);
      let isAdd = true;
      arr.map(item => {
        if (item.catalogId === node.catalogId) {
          item.catalogName = node.catalogName;
          item.catalogDesc = node.catalogDesc;
          isAdd = false;
        }
      });
      if (isAdd) {
        arr = arr.concat(node);
      }

      setTreeData(arr);
      saveTreeData(arr);
      setSelectedKeysArr([`${node.catalogId}`]);
      saveCatalogAddVisible(false);
      // saveMenuID(node.catalogId);
    });
    return () => {
      PubSub.unsubscribe(`${eventName}`);
    };
  }, []);

  const queryTreeData = () => {
    setLoading(true);
    request('pmc/pcms/formCatalog/query', {
      method: 'GET',
    }).then(res => {
      if (res && res.success == true) {
        let node = {};
        let arr = [];
        res.data.map((item, index) => {
          node = item;
          // if (item.menuType === '1000') {
          node.isLeaf = false;
          // } else {
          //   node.isLeaf = true;
          // }
          arr.push(node);
        });
        setTreeData(arr);
        setLoading(false);
        saveTreeData(arr);
      }
    });
  };

  // 由接口决定，根据parMenuId 获取同级元素
  const getParentId = parCatalogId => {
    return TreeData.filter(item => {
      return item.parCatalogId === parCatalogId;
    });
  };

  // 对树进行了扩展操作
  const renderTreeNode = parCatalogId => {
    const tmp = getParentId(parCatalogId);
    if (tmp.length > 0) {
      return tmp.map(item => {
        const index = item.catalogName.indexOf(searchValue);
        const beforeStr = item.catalogName.substr(0, index);
        const afterStr = item.catalogName.substr(index + searchValue.length);
        let title = '';

        if (item.isLeaf) {
          title = (
            <span>
              {/* <span style={{ paddingRight: '8px' }}>{item.catalogName}</span> */}
              {index > -1 ? (
                <span>
                  {beforeStr}
                  <span style={{ color: '#f50' }}>{searchValue}</span>
                  {afterStr}
                </span>
              ) : (
                <span>{item.catalogName}</span>
              )}

              <span className={styles.system_form_tree_edit}>
                <Tooltip title="编辑">
                  <Icon
                    type="edit"
                    className={styles.icon}
                    onClick={event => {
                      edit(event, item);
                    }}
                  />
                </Tooltip>
                <Tooltip title="删除">
                  <Icon
                    type="delete"
                    className={styles.icon}
                    onClick={event => {
                      removeTree(event, item);
                    }}
                  />
                </Tooltip>
              </span>
            </span>
          );
        } else {
          if (getParentId(item.catalogId).length === 0) {
            title = (
              <span>
                {index > -1 ? (
                  <span>
                    {beforeStr}
                    <span style={{ color: '#f50' }}>{searchValue}</span>
                    {afterStr}
                  </span>
                ) : (
                  <span>{item.catalogName}</span>
                )}
                <span className={styles.system_form_tree_edit}>
                  <Tooltip title="编辑">
                    <Icon
                      type="edit"
                      className={styles.icon}
                      onClick={event => {
                        edit(event, item);
                      }}
                    />
                  </Tooltip>
                  <Tooltip title="新增">
                    <Icon
                      type="plus-circle"
                      className={styles.icon}
                      onClick={event => {
                        add(event, item);
                      }}
                    />
                  </Tooltip>
                  <Tooltip title="删除">
                    <Icon
                      type="delete"
                      className={styles.icon}
                      onClick={event => {
                        removeTree(event, item);
                      }}
                    />
                  </Tooltip>
                </span>
              </span>
            );
          } else {
            title = (
              <span>
                {index > -1 ? (
                  <span>
                    {beforeStr}
                    <span style={{ color: '#f50' }}>{searchValue}</span>
                    {afterStr}
                  </span>
                ) : (
                  <span>{item.catalogName}</span>
                )}
                <span className={styles.system_form_tree_edit}>
                  <Tooltip title="编辑">
                    <Icon
                      type="edit"
                      className={styles.icon}
                      onClick={event => {
                        edit(event, item);
                      }}
                    />
                  </Tooltip>
                  <Tooltip title="新增">
                    <Icon
                      type="plus-circle"
                      className={styles.icon}
                      onClick={event => {
                        add(event, item);
                      }}
                    />
                  </Tooltip>
                </span>
              </span>
            );
          }
        }
        return (
          <TreeNode
            icon={({ expanded, isLeaf }) => (
              <Icon type={expanded ? 'folder-open' : isLeaf ? 'file' : 'folder'} />
            )}
            title={title}
            key={item.catalogId}
            isLeaf={item.isLeaf}
            dataRef={item}
          >
            {renderTreeNode(item.catalogId)}
          </TreeNode>
        );
      });
    }
  };

  // 选中节点
  const selectTreeNode = (selectedKeys, e) => {
    // if (props.behavior === 'disable') {
    setSelectedKeysArr(selectedKeys);
    if (selectedKeys[0] !== undefined) {
      saveSelectCatalog(e.node.props.dataRef);
      saveCatalogButton(true);
    } else {
      saveSelectCatalog({});
      saveCatalogButton(false);
    }

    // saveCatalogAddVisible('disable');
    // }
  };
  // 编辑节点
  const edit = (event, item) => {
    event.stopPropagation();
    event.nativeEvent.stopImmediatePropagation();

    setSelectedKeysArr([`${item.catalogId}`]);
    saveSelectCatalog(item);
    saveCatalogAddVisible(true);
    saveCatalogAddType('edit');
    saveIsLeaf(item.isLeaf);
    saveCatalogButton(true);
  };
  // 添加子节点
  const add = (event, item) => {
    event.stopPropagation();
    event.nativeEvent.stopImmediatePropagation();

    setSelectedKeysArr([`${item.catalogId}`]);
    saveSelectCatalog(item);
    saveCatalogAddVisible(true);
    saveCatalogAddType('addSon');
    saveIsLeaf(item.isLeaf);
    saveCatalogButton(true);
  };
  //删除节点
  const removeTree = (event, item) => {
    event.stopPropagation();
    event.nativeEvent.stopImmediatePropagation();
    Modal.confirm({
      content: `确认删除目录“${item.catalogName}”及其对应组件？`,
      okText: '确定',
      cancelText: '取消',
      onOk() {
        request('pmc/pcms/formCatalog/delete', {
          method: 'GET',
          data: { catalogId: item.catalogId },
        }).then(res => {
          if (res && res.success == true) {
            let arr = [...TreeData];

            const i = findIndex(TreeData, { catalogId: item.catalogId });
            if (i !== -1) {
              arr.splice(i, 1);
            }
            setTreeData(arr);
            saveTreeData(arr);
            saveSelectCatalog({});
            saveCatalogButton(false);

            message.success('删除成功');
          } else {
            if (res && res.errMessage) {
              message.error(res.errMessage);
            } else {
              message.error('删除失败');
            }
          }
        });
      },
    });
  };

  const onSearch = value => {
    if (!value) {
      setExpandedKeys(['']);
      setAutoExpandParent(false);
      setSearchValue('');
      return;
    }
    let searchArr = []; // 被选中项
    let parentArr = []; // 当前选中项的父节点
    const getAllparentId = parentId => {
      TreeData.filter(item => {
        if (item.catalogId === parentId) {
          parentArr.push(item.catalogId);
          if (item.parCatalogId != 0) {
            getAllparentId(item.parCatalogId);
          }
        }
      });
    };
    TreeData.map(item => {
      if (item.catalogName.indexOf(value) > -1) {
        searchArr.push(item.catalogId);
        getAllparentId(item.parCatalogId);
      }
    }).filter((item, i, self) => item && self.indexOf(item) === i);
    const strParentArr = [];
    parentArr.map(item => {
      strParentArr.push(`${item}`);
    });
    const strSearchArr = [];
    searchArr.map(item => {
      strSearchArr.push(`${item}`);
    });
    setExpandedKeys(strParentArr);
    setAutoExpandParent(true);
    setSearchValue(value);
  };

  const onExpand = expandedKeys => {
    setExpandedKeys(expandedKeys);
    setAutoExpandParent(false);
  };

  return (
    <div className={styles.system_form}>
      <div className={styles.system_form_search}>
        <Search style={{ marginBottom: 8 }} placeholder="搜索关键字" onSearch={onSearch} />
      </div>
      <ScrollBar autoHide autoHeight autoHeightMax={props.height - 100}>
        <Spin spinning={loading}>
          <Tree
            showIcon
            expandAction="false"
            className={styles.system_form_tree}
            onSelect={selectTreeNode}
            selectedKeys={selectedKeysArr}
            // ==
            onExpand={onExpand}
            expandedKeys={expandedKeys}
            autoExpandParent={autoExpandParent}
          >
            {renderTreeNode(0)}
          </Tree>
        </Spin>
      </ScrollBar>
    </div>
  );
}

// export default CatalogInfo;
export default connect(({ formManage }) => ({
  // behavior: formManage.behavior,
}))(CatalogInfo);
// className={classNames('ant-upload-list', 'ant-upload-list-picture-card')}
